package org.yanghaokun.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //我们需要拿到前端放在请求头的token
        String token = request.getHeader("token");
        //这里如果每次都能拿到token的话说明是有登陆过的，所以每次请求我们都刷新一下时间
        if (!StringUtils.isEmpty(token)) {
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) {
                //不为空有登陆信息我们就刷新时间
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //走到这里的都是登陆失败的，需要返回一个错误信息
        //设置字符集,因为是反给前端的，所以这里用response
        response.setCharacterEncoding("utf-8");
        //设置请求体类型
        response.setContentType("application/json; charset=UTF-8");
        //以json的格式写上错误信息传给前台
        PrintWriter writer = response.getWriter();
        //{"success":false, "message":"no-login"}
        writer.write("{\"success\":false, \"message\":\"no-login\"}");
        //关流
        writer.close();
        return false;
    }
}
